<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="单号" prop="billId" v-if="dataForm.id !=0">
        <el-input v-model="dataForm.billId" placeholder="单号"></el-input>
      </el-form-item>
      <el-form-item label="收款时间" prop="createTime">
        <el-input v-model="dataForm.createTime" readonly></el-input>
      </el-form-item>
      <el-form-item label="制单人" prop="createUserName">
        <el-input v-model="dataForm.createUserName" readonly></el-input>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-select v-model="dataForm.customerName">
          <el-option v-for="item in customerOptions" :value="item.name" :label="item.name" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收款类型" prop="type">
        <el-radio-group v-model="dataForm.type" @change="changeType">
          <el-radio label="1">批发收款</el-radio>
          <el-radio label="2">调帐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="本次核销金额" prop="writeOffAmount">
        <el-input v-model="dataForm.writeOffAmount" placeholder="本次核销金额" readonly></el-input>
      </el-form-item>
      <el-form-item label="本次收款金额" prop="receiptAmount">
        <el-input v-model="dataForm.receiptAmount" placeholder="本次收款金额"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input v-model="dataForm.memo" placeholder="备注"></el-input>
      </el-form-item>

      <el-tabs type="border-card" v-if="dataForm.type == 1">
        <el-divider content-position="left">单据信息</el-divider>
        <el-row>
          <el-button type="primary" icon="el-icon-plus" @click.prevent="getInfo()">选择单据</el-button>
          <el-button type="primary" icon="el-icon-delete" @click.prevent="delTableData()">删除</el-button>
        </el-row>
        <div class="avue-crud">
          <el-table :data="dataList" border @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="linkBillId" label="单据编号"></el-table-column>
            <el-table-column prop="linkBillType" label="单据类型"></el-table-column>
            <el-table-column prop="linkBillType" label="单据日期"></el-table-column>
            <el-table-column prop="allReceiptAmount" label="单据金额"></el-table-column>
            <el-table-column prop="doneReceiptAmount" label="已收金额"></el-table-column>
            <el-table-column prop="notWriteOffAmount" label="未收金额"></el-table-column>
            <el-table-column prop="receiptAmount" label="收款金额">
              <template slot-scope="scope">
                <el-input v-model="scope.row.receiptAmount" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="memo" label="摘要">
              <template slot-scope="scope">
                <el-input v-model="scope.row.memo" style="width: 100px;"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tabs>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="ischeck">确定</el-button>
      <el-switch v-model="dataForm.status" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"></el-switch>
    </span>
  </el-dialog>
</template>

<script>
  import {
    getObj,
    addObj,
    putObj
  } from '@/api/eims/receipt'
  import {
    mapGetters
  } from "vuex";
  export default {
    data() {
      return {
        visible: false,
        ischeck: false,
        dataForm: {
          id: 0,
          billId: '',
          writeOffAmount: '0.00',
          receiptAmount: '0.00',
          customerName: '',
          supplyId: '',
          supplyName: '',
          status: '0',
          type: '1',
          memo: '',
          auditUser: '',
          auditUserName: '',
          auditTime: '',
          createTime: '',
          updateTime: '',
          createUser: '',
          modifyUser: '',
          createUserName: '',
          orgId: '',
          tenantId: '',
          unitId: '',
          detailList: []
        },
        dataList: [],
        customerOptions: [],
        dataRule: {
          billId: [{
            required: true,
            message: '单号不能为空',
            trigger: 'blur'
          }],
          writeOffAmount: [{
            required: true,
            message: '本次核销金额不能为空',
            trigger: 'blur'
          }],
          receiptAmount: [{
            required: true,
            message: '本次收款金额不能为空',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '单据类型不能为空',
            trigger: 'blur'
          }],
          createTime: [{
            required: true,
            message: '收款时间不能为空',
            trigger: 'blur'
          }],
          createUserName: [{
            required: true,
            message: '制单人不能为空',
            trigger: 'blur'
          }]
        }
      }
    },
    computed: {
      ...mapGetters(["userInfo"])
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        if (this.dataForm.id == 0) {
          this.dataForm.createUserName = this.userInfo.realName;
          this.timeFormate(new Date());
          this.dataForm.status = '0';
          this.dataForm.writeOffAmount = '0.00';
          this.dataForm.receiptAmount = '0.00';

        }
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id).then(response => {
              if(response.data.code == '0'){
                this.dataForm = response.data.data.data
                this.dataList = response.data.data.detailList
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              putObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            } else {
              this.dataForm.createTime = ''
              addObj(this.dataForm).then(response => {
                if(response.data.code == '0'){
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                }else{
                  this.$message.error(response.data.msg)
                }
                this.ischeck = false
              }).catch(() => {
                this.ischeck = false
              })
            }
          }else{
            this.ischeck = false
          }
        })
      },
      changeType() {
        this.dataList = []
      },
      handleSelectionChange(val) {
        this.selectionList = val
      },
      //  合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        sums[3] = '合计： '
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == 7 || index == 4 || index == 5 || index == 6) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });

        this.$set(this.dataForm, 'writeOffAmount', sums[6] || '0.00')
        // this.$set(this.dataForm, 'receiptAmount', sums[7]  || '0.00')
        return sums;
      },
      //显示当前时间（年月日时分秒）
      timeFormate(timeStamp) {
        let year = new Date(timeStamp).getFullYear();
        let month =
          new Date(timeStamp).getMonth() + 1 < 10 ?
          "0" + (new Date(timeStamp).getMonth() + 1) :
          new Date(timeStamp).getMonth() + 1;
        let date =
          new Date(timeStamp).getDate() < 10 ?
          "0" + new Date(timeStamp).getDate() :
          new Date(timeStamp).getDate();
        let hh =
          new Date(timeStamp).getHours() < 10 ?
          "0" + new Date(timeStamp).getHours() :
          new Date(timeStamp).getHours();
        let mm =
          new Date(timeStamp).getMinutes() < 10 ?
          "0" + new Date(timeStamp).getMinutes() :
          new Date(timeStamp).getMinutes();
        let ss =
          new Date(timeStamp).getSeconds() < 10 ?
          "0" + new Date(timeStamp).getSeconds() :
          new Date(timeStamp).getSeconds();
        this.nowTime =
          "POUT" +
          year +
          "" +
          month +
          "" +
          date +
          "" +
          hh +
          "" +
          mm +
          "" +
          ss +
          this.dataForm.deptId;
        this.dataForm.createTime = year + "-" + month + "-" + date;
      },
      //根据获取采购单
      getInfo() {
        if (!this.dataForm.customerName) {
          this.$message.warning("请选择客户")
          return
        }
        //todo 新增单据弹窗
      },
      // 删除选中的商品
      delTableData() {
        this.selectionList.forEach((item, index) => {
          for (let i = 0; i < this.dataList.length; i++) {
            if (this.dataList[i] == item) {
              this.dataList.splice(i, 1)
              this.dataForm.detailList.splice(i, 1)
            }
          }
          this.selectionList = []
        })
      },
    }
  }
</script>
